package com.hmdp.utils;

import cn.hutool.core.util.BooleanUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.hmdp.entity.Shop;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
import java.util.function.Function;

@Component
@Slf4j
@RequiredArgsConstructor
public class CacheClient {
    private final StringRedisTemplate stringRedisTemplate;
    private static  final ExecutorService CACHE_REBUILD_EXCUTEOR = Executors.newFixedThreadPool(10);
    private boolean tryLock(String key){
        Boolean flag = stringRedisTemplate.opsForValue().setIfAbsent(key, "1", 10, TimeUnit.SECONDS);
        return BooleanUtil.isTrue(flag);
    }
    private void unlock(String key){
        stringRedisTemplate.delete(key);
    }

    public void set(String key, Object value, Long time, TimeUnit timeUnit) {
        stringRedisTemplate.opsForValue().set(key, JSONUtil.toJsonStr(value), time, timeUnit);
    }

    public void setWithLogicalExpire(String key, Object value, Long time, TimeUnit timeUnit) {
        // 设置逻辑过期
        RedisData redisData = new RedisData();
        redisData.setData(value);
        redisData.setExpireTime(LocalDateTime.now().plusSeconds(timeUnit.toSeconds(time)));
        // 写入redis
        stringRedisTemplate.opsForValue().set(key, JSONUtil.toJsonStr(redisData));
    }

    // 解决缓存穿透
    public <R,ID> R queryWithPassThrough(String keyPrefix, ID id, Class<R> type, Function<ID,R> function, Long time, TimeUnit timeUnit) {
        // 1. 从redis中查询商铺
        String key = keyPrefix + id;
        String json = stringRedisTemplate.opsForValue().get(key);
        // 2. redis中能查到则直接返回商铺信息
        if(StrUtil.isNotBlank(json)){
            return JSONUtil.toBean(json, type);
        }
        //  判断命中的是否为空值，
        if(json != null){
            return null;
        }
        // 3. 什么都没有命中
        // 3.1 根据id查询数据库
        R r = function.apply(id);

        // 3.2 判断查出来的商铺是否存在，不存在设置空值
        if(r == null){
            // 设置空值
            stringRedisTemplate.opsForValue().set(key,"", RedisConstants.CACHE_SHOP_TTL, TimeUnit.MINUTES);
            return null;
        }
        // 3.3 存入redis中
            this.set(key, r, time, timeUnit);
        // 3.4 返回信息
        return r;
    }

    // 解决缓存击穿
    public <R,ID> R queryWithLogicExpire(String keyPrefix,String lockKeyPrefix, ID id, Class<R> type, Function<ID,R> function, Long time, TimeUnit timeUnit){
        // 1. 从redis中查询商铺
        String key = keyPrefix + id;
        String json = stringRedisTemplate.opsForValue().get(key);
        // 2. redis中能查到则直接返回商铺信息
        if(StrUtil.isBlank(json)){
            return null;
        }
        // 4. 命中，先把json反序列化为对象
        RedisData redisData = JSONUtil.toBean(json, RedisData.class);
        R r = JSONUtil.toBean((JSONObject) redisData.getData(), type);
        LocalDateTime expireTime = redisData.getExpireTime();
        // 5. 判断是否过期
        if(LocalDateTime.now().isAfter(expireTime)){
            // 5.1 未过期返回缓存中的信息
            return r;
        }
        // 6.过期
        // 6.1尝试获取互斥锁，缓存重建
        String lockKey = lockKeyPrefix + id;
        boolean tryLock = tryLock(lockKey);

        // 6.2 判断是否成功
        if(tryLock){
            // 6.3 获取成功，开启线程，实现缓存重建
            CACHE_REBUILD_EXCUTEOR.submit(() -> {
                try {
                    // 重建缓存
                        // 查数据库
                    R r1 = function.apply(id);
                    // 写redis
                    setWithLogicalExpire(key,r1,time,timeUnit);
                } catch (Exception e) {
                    throw new RuntimeException(e);
                } finally {
                    // 释放锁
                    unlock(lockKey);
                }
            });
        }
        // 6.4 返回过期商铺信息
        return r;
    }

}
